package com.centling.smartSealForPhone.activity

import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.View
import com.centling.smartSealForPhone.R
import com.centling.smartSealForPhone.bean.DetailBean
import com.centling.smartSealForPhone.constants.UrlConstants
import com.centling.smartSealForPhone.utils.ImageUtil
import com.centling.smartSealForPhone.utils.OkHttpUtil
import com.centling.smartSealForPhone.utils.ShowToast
import com.example.localalbum.common.LocalImageHelper
import com.example.localalbum.ui.PagerView
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_review_details.*
import java.io.Serializable
import java.util.*

class ReviewDetailsActivity : TitleBarActivity() {

    private var detailBean: DetailBean? = null

    private val userList = ArrayList<String>()
    private val fileList = ArrayList<String>()

    private var picList = ArrayList<String>()
    private var nameList = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_review_details)

        setTitleBarText("复审详情")

        initView()

        sendRequestToFetchInfo()

        sendRequestToMakeIllegalMark()
    }

    private fun initView() {
        if (intent.getBooleanExtra("state", true)) {
            tv_review_detail_start_upload.visibility = View.GONE
        }
        tv_review_detail_start_upload.setOnClickListener(View.OnClickListener {
            if (detailBean == null) {
                return@OnClickListener
            }
            val intent = Intent(this@ReviewDetailsActivity, ReviewUploadActivity::class.java)
            intent.putExtra("sealApplyId", getIntent().getStringExtra("sealApplyId"))
            startActivity(intent)
            finish()
        })
    }

    private fun sendRequestToFetchInfo() {
        mProcessDialog.setTitle("正在获取详情").showNormal()
        getEnqueue(String.format(Locale.CHINA, UrlConstants.DETAIL_NEW, intent.getStringExtra("sealApplyId")),
                object : OkHttpUtil.NetCallBack {
                    override fun onSucceed(json: String?) {
                        mProcessDialog.dismiss()

                        detailBean = Gson().fromJson(json, DetailBean::class.java)
                        setData(detailBean!!)
                    }

                    override fun onFailed(reason: String?) {
                        mProcessDialog.dismiss()
                        ShowToast.shortTime(reason)
                        finish()
                    }
                })
    }

    private fun sendRequestToMakeIllegalMark() {
        val params = HashMap<String,String>()
        postJsonEnqueue(String.format(Locale.CHINA, UrlConstants.REVIEW_ILLEGAL_READ, intent.getStringExtra("sealApplyId")),params,
                object : OkHttpUtil.NetCallBack {
                    override fun onSucceed(json: String?) {
                    }

                    override fun onFailed(reason: String?) {
                    }
                })
    }

    private fun setData(bean: DetailBean) {
        if (bean.isValid == "0") {
            tv_review_detail_is_valid.text = "正常"
        } else {
            tv_review_detail_is_valid.text = "换章失效"
            tv_review_detail_start_upload.isClickable = false
            tv_review_detail_start_upload.visibility = View.GONE
        }

        tv_review_detail_user_name.text = bean.applicantUserName
        tv_review_detail_seal_reg.text = bean.sealReg
        tv_review_detail_apply_date.text = bean.applyDate
        tv_review_detail_apply_people.text = bean.applyOperator
        tv_review_detail_failed_date.text = bean.reviewcreatetimeReal
        tv_review_detail_apply_reason.text = "${bean.applyReasonType}${if (TextUtils.isEmpty(bean.applyReason)) "" else ":" }${bean.applyReason}"

        tv_review_detail_apply_time.text = bean.applyDate

        tv_review_detail_approval_history.setOnClickListener {
            if (bean.sealApplyAuditRecordList != null && !bean.sealApplyAuditRecordList.isEmpty()) {
                startActivity(Intent(mContext, HistoryApprovalRecordsActivity::class.java).putParcelableArrayListExtra("history_stamp_records", bean.sealApplyAuditRecordList as ArrayList<out Parcelable>))
            } else {
                ShowToast.shortTime("没有审阅记录")
            }
        }

        /**
         * stamp pics
         */
        val stampPics = bean.sealPic.split(",".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
        val spics = ArrayList<String>()
        for (i in stampPics.indices) {
            spics.add(stampPics[i])
        }
        sv_stamp_pics.addFiles(spics)

        userList.add(bean.applicantUserAvatar)
        ImageUtil.loadImage(userList[0], iv_review_user_head, R.drawable.iv_avatar_default)
        iv_review_user_head.setOnClickListener {
            val pictures: MutableList<LocalImageHelper.LocalFile> = ArrayList()
            val file = LocalImageHelper.LocalFile()
            file.originalUri = userList[0]
            file.thumbnailUri = userList[0]
            pictures.add(file)
            val intent = Intent(mContext, PagerView::class.java)
            intent.putExtra("FILE_LIST", pictures as Serializable)
            intent.putExtra("INDEX", 0)
            mContext.startActivity(intent)
        }

        val files = bean.docPics.split(",".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
        for (i in files.indices) {
            fileList.add(files[i])
        }
        sv_review_apply_file.addFiles(fileList)

        tv_review_detail_use_reason.text = bean.reviewFailReason
        val pics = bean.pics.split("[,|]".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
        if (!TextUtils.isEmpty(bean.pics) && !pics.isEmpty()) {
            var i = 0
            while (i < pics.size) {
                picList.add(pics[i])
                i += 2
            }
            var j = 1
            while (j < pics.size) {
                nameList.add(pics[j])
                j += 2
            }

            scroll_img_pic!!.addFiles(picList, nameList)
        } else {
            tv_review_detail_failed_pic_tips.visibility = View.GONE
            scroll_img_pic.visibility = View.GONE
        }
    }
}
